package com.zfb.videoscript.core

import android.accessibilityservice.AccessibilityService
import android.content.Context
import kotlinx.coroutines.*
import kotlin.random.Random

class ScriptEngine(private val service: AccessibilityService) {
    private var isRunning = false
    private val coroutineScope = CoroutineScope(Dispatchers.Default + Job())
    private val logManager = LogManager(service.applicationContext)
    private val nodeLocator = NodeLocator(service)
    private val actionController = ActionController(service, nodeLocator, logManager)
    
    data class ScriptConfig(
        val speed: Int = 800,
        val startDelay: Int = 21,
        val endDelay: Int = 30,
        val likeRate: Int = 66,
        val checkRedPacket: Boolean = true,
        val isPDD: Boolean = false,
        val randomRange: Int = 50,  // 随机范围
        val swipeDuration: Long = 300  // 滑动持续时间
    )

    fun start(config: ScriptConfig) {
        if (isRunning) return
        isRunning = true
        
        coroutineScope.launch {
            try {
                logManager.logOperation("脚本开始运行", "使用配置: $config")
                var swipeCount = 0
                var likeCount = 0
                var failCount = 0
                
                // 获取平台配置
                val platformConfig = nodeLocator.getConfig(if (config.isPDD) "pdd" else "alipay")
                if (platformConfig == null) {
                    logManager.logOperation("启动失败", "未找到平台配置")
                    stop()
                    return@launch
                }
                
                while (isRunning) {
                    // 更新当前节点树
                    nodeLocator.updateCurrentNode()
                    
                    // 基础延迟
                    delay(config.speed.toLong())
                    
                    // 随机延迟
                    val randomDelay = Random.nextInt(
                        config.startDelay * 1000,
                        config.endDelay * 1000
                    )
                    delay(randomDelay.toLong())
                    
                    // 检查红包按钮
                    if (config.checkRedPacket && actionController.checkRedPacket(platformConfig)) {
                        logManager.logOperation("检测到红包", "自动停止脚本")
                        stop()
                        return@launch
                    }
                    
                    // 随机点赞
                    if (Random.nextInt(100) < config.likeRate) {
                        val success = actionController.performLike(platformConfig)
                        if (success) {
                            likeCount++
                            if (likeCount % 10 == 0) {
                                logManager.logOperation("点赞统计", "已点赞 $likeCount 次")
                            }
                        }
                    }
                    
                    // 执行上滑
                    val success = actionController.performSwipe(
                        startX = actionController.addRandomness(540, config.randomRange).toFloat(),
                        startY = actionController.addRandomness(1600, config.randomRange).toFloat(),
                        endX = actionController.addRandomness(540, config.randomRange).toFloat(),
                        endY = actionController.addRandomness(400, config.randomRange).toFloat(),
                        duration = config.swipeDuration
                    )
                    
                    if (success) {
                        swipeCount++
                        if (swipeCount % 50 == 0) {
                            logManager.logOperation("滑动统计", "已滑动 $swipeCount 次")
                        }
                        failCount = 0
                    } else {
                        failCount++
                        if (failCount >= 3) {
                            logManager.logOperation("脚本停止", "连续失败次数过多")
                            stop()
                            return@launch
                        }
                    }
                }
            } catch (e: Exception) {
                logManager.logOperation("脚本异常", e.message ?: "未知错误")
                e.printStackTrace()
                stop()
            } finally {
                nodeLocator.clearCurrentNode()
            }
        }
    }

    fun stop() {
        if (isRunning) {
            coroutineScope.launch {
                logManager.logOperation("脚本停止", "正常停止")
            }
        }
        isRunning = false
        coroutineScope.coroutineContext.cancelChildren()
    }
} 